#!/usr/bin/env node

/**
 * 测试1267指令 - 物品基础表查询功能
 * 请求格式: { c: 1267, d: { id } }
 * 返回格式: {"act_id":1267,"code":0,"data":[{"k":"名称:","v":"跌打药"},{"k":"价格:","v":"50两"},{"k":"等级:","v":"1"},{"k":"负重:","v":"1"},{"k":"介绍:","v":"散瘀消肿，强筋健骨，可迅速补充气血。"}]}
 */

const WebSocket = require('ws');

class ItemQueryTester {
    constructor() {
        this.ws = null;
        this.testResults = [];
    }

    async connect() {
        console.log('🔌 连接到WebSocket服务器...');

        return new Promise((resolve, reject) => {
            this.ws = new WebSocket('ws://localhost:3000/user-service/websocket');

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });
        });
    }

    async login() {
        console.log('\n🔐 步骤1: 用户登录...');

        const loginMessage = {
            c: 0,
            d: {
                username: "testuser",
                password: "testpass"
            }
        };

        this.ws.send(JSON.stringify(loginMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 登录超时，继续测试...');
                resolve();
            }, 5000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 登录响应:', JSON.stringify(response, null, 2));
                    resolve();
                } catch (error) {
                    console.log('⚠️ 登录响应解析失败，继续测试...');
                    resolve();
                }
            });
        });
    }

    async selectCharacter() {
        console.log('\n👤 步骤2: 选择角色...');

        const selectMessage = {
            c: 3,
            d: {
                roleId: 1
            }
        };

        this.ws.send(JSON.stringify(selectMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 角色选择超时，继续测试...');
                resolve();
            }, 5000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 角色选择响应:', JSON.stringify(response, null, 2));
                    resolve();
                } catch (error) {
                    console.log('⚠️ 角色选择响应解析失败，继续测试...');
                    resolve();
                }
            });
        });
    }

    async testItemQuery(itemId) {
        console.log(`\n🔍 步骤3: 测试物品查询 (ID: ${itemId})...`);

        const queryMessage = {
            c: 1267,
            d: {
                id: itemId
            }
        };

        console.log('📤 发送请求:', JSON.stringify(queryMessage, null, 2));
        this.ws.send(JSON.stringify(queryMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 物品查询超时');
                this.addTestResult(`物品查询测试 (ID: ${itemId})`, false, '查询超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 查询响应:', JSON.stringify(response, null, 2));

                    // 验证响应格式
                    if (response.act_id === 1267) {
                        if (response.code === 0 && response.data && Array.isArray(response.data)) {
                            console.log('✅ 物品查询成功');
                            console.log('📋 物品信息:');
                            response.data.forEach(item => {
                                console.log(`   ${item.k} ${item.v}`);
                            });
                            this.addTestResult(`物品查询测试 (ID: ${itemId})`, true, '查询成功');
                        } else {
                            console.log('❌ 物品查询失败:', response.msg || '未知错误');
                            this.addTestResult(`物品查询测试 (ID: ${itemId})`, false, response.msg || '查询失败');
                        }
                    } else {
                        console.log('⚠️ 响应格式不符合预期');
                        this.addTestResult(`物品查询测试 (ID: ${itemId})`, false, '响应格式错误');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult(`物品查询测试 (ID: ${itemId})`, false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    async testInvalidItemQuery() {
        console.log('\n🚫 步骤4: 测试无效物品ID...');

        const invalidQueryMessage = {
            c: 1267,
            d: {
                id: 99999  // 不存在的物品ID
            }
        };

        console.log('📤 发送请求:', JSON.stringify(invalidQueryMessage, null, 2));
        this.ws.send(JSON.stringify(invalidQueryMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 无效物品查询超时');
                this.addTestResult('无效物品查询测试', false, '查询超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 查询响应:', JSON.stringify(response, null, 2));

                    // 验证错误响应
                    if (response.act_id === 1267 && response.code === -1) {
                        console.log('✅ 无效物品查询正确处理');
                        this.addTestResult('无效物品查询测试', true, '正确处理无效ID');
                    } else {
                        console.log('❌ 无效物品查询处理不正确');
                        this.addTestResult('无效物品查询测试', false, '未正确处理无效ID');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult('无效物品查询测试', false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    async testInvalidParameters() {
        console.log('\n🚫 步骤5: 测试无效参数...');

        const invalidParamMessage = {
            c: 1267,
            d: {
                // 缺少id参数
            }
        };

        console.log('📤 发送请求:', JSON.stringify(invalidParamMessage, null, 2));
        this.ws.send(JSON.stringify(invalidParamMessage));

        return new Promise((resolve) => {
            const timeout = setTimeout(() => {
                console.log('⚠️ 无效参数查询超时');
                this.addTestResult('无效参数测试', false, '查询超时');
                resolve();
            }, 10000);

            this.ws.once('message', (data) => {
                clearTimeout(timeout);
                try {
                    const response = JSON.parse(data.toString());
                    console.log('📨 查询响应:', JSON.stringify(response, null, 2));

                    // 验证错误响应
                    if (response.act_id === 1267 && response.code === -1) {
                        console.log('✅ 无效参数正确处理');
                        this.addTestResult('无效参数测试', true, '正确处理无效参数');
                    } else {
                        console.log('❌ 无效参数处理不正确');
                        this.addTestResult('无效参数测试', false, '未正确处理无效参数');
                    }
                    resolve();
                } catch (error) {
                    console.log('❌ 响应解析失败:', error.message);
                    this.addTestResult('无效参数测试', false, '响应解析失败');
                    resolve();
                }
            });
        });
    }

    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message
        });
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！');
        } else {
            console.log('⚠️ 部分测试失败，请检查实现。');
        }
    }

    async disconnect() {
        console.log('\n🔌 断开连接...');
        if (this.ws) {
            this.ws.close();
            console.log('✅ 连接已断开');
        }
    }

    async runAllTests() {
        try {
            await this.connect();
            await this.login();
            await this.selectCharacter();

            // 测试一些常见的物品ID
            await this.testItemQuery(1);   // 跌打药
            await this.testItemQuery(2);   // 其他物品
            await this.testItemQuery(71);  // 杂物类物品

            await this.testInvalidItemQuery();
            await this.testInvalidParameters();

            this.printTestResults();

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
        } finally {
            await this.disconnect();
        }
    }
}

// 运行测试
if (require.main === module) {
    const tester = new ItemQueryTester();
    tester.runAllTests().catch(console.error);
}

module.exports = ItemQueryTester;
